package com.test.javafaq_search.service.impl;

import com.github.pagehelper.PageInfo;
import com.test.javafaq_commons.entity.Tag;
import com.test.javafaq_commons.entity.User;
import com.test.javafaq_search.repository.QuestionRepository;
import com.test.javafaq_search.service.IQuestionService;
import com.test.javafaq_search.vo.Pages;
import com.test.javafaq_search.vo.QuestionVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class QuestionServiceImpl implements IQuestionService {

    @Resource
    QuestionRepository questionRepository;

    @Resource
    RestTemplate restTemplate;

    @Override
    public void saveQuestion(QuestionVo questionVo) {
        questionRepository.save(questionVo);
    }


    //调用faq模块提供的查询所有标签的服务
//并转换为Map格式赋值给name2TagMap属性
    private final Map<String, Tag> name2TagMap=
            new ConcurrentHashMap<>();
    //方法开始
    private Map<String, Tag> getName2TagMap(){
        if(name2TagMap.isEmpty()){
            String url="http://faq-service/v1/tags/list";
            Tag[] tags=restTemplate.getForObject(
                    url,Tag[].class);
            for(Tag t: tags ){
                name2TagMap.put(t.getName(),t);
            }
        }
        return name2TagMap;
    }

    //编写一个方法,这个方法能将tagNames字符串返回为List<Tag>
    private List<Tag> tagNamesToTags(String tagNames) {
        //Java基础,Java SE,面试题
        String[] names = tagNames.split(",");
        //names={"Java基础","Java SE","面试题"}
        List<Tag> tags = new ArrayList<>();
        Map<String, Tag> map = getName2TagMap();
        //循环遍历所有names中的元素,获得元素对应的tag对象,保存到list中
        for (String tagName : names) {
            Tag t = map.get(tagName);
            tags.add(t);
        }
        return tags;
    }

    //调用sys获取用户信息
    private User getUser(String username){
        String url = "http://sys-service/v1/auth/user?username={1}";
        User user = restTemplate.getForObject(url, User.class, username);
        return user;
    }


    @Override
    public PageInfo<QuestionVo> search(String keyWord, String username, Integer pageNum, Integer pageSize) {
        if(pageNum == null){
            pageNum = 1;
        }
        if (pageSize == null){
            pageSize = 3;
        }
        User user = getUser(username);
        //spring data 的页码从0开始
        int num = pageNum - 1;
        //带排序的分页编写
        PageRequest pageable = PageRequest.of(num, pageSize, Sort.Direction.DESC, "pageViews");
        //执行ES查询
        Page<QuestionVo> page = questionRepository.queryAllByParams(keyWord, keyWord, user.getId(), pageable);

        //遍历QuestionVo，添加tags
        for (QuestionVo q : page.getContent()) {
            List<Tag> tags = tagNamesToTags(q.getTagNames());
            q.setTags(tags);
        }

        //转型成PageInfo
        return Pages.pageInfo(page);
    }

    @Override
    public void sync() {
        String url = "http://faq-service/v1/questions/page/count?pageSize={1}";
        int pageSize = 10;

        int pages = restTemplate.getForObject(url,Integer.class,pageSize);

        for (int i = 1; i < pages; i++) {
            url = "http://faq-service/v1/questions/page?pageNum={1}&pageSize={2}";
            QuestionVo[] questions = restTemplate.getForObject(url, QuestionVo[].class, i, pages);
            questionRepository.saveAll(Arrays.asList(questions));
        }

    }
}
